# 新的干净的views.py文件
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import Q, Count
from django.conf import settings
from utils.auth_decorators import login_required, permission_required, rate_limit, secure_api
from utils.data_iterators import MedicalDataIteratorFactory
from .models import Department, Doctor, Appointment, MedicalArticle, HealthRecord
from datetime import datetime, timedelta
import json
try:
    from utils.amap_decorators import amap_call
except ImportError:
    def amap_call(func):
        return func

try:
    from utils.amap import amap_call, extract_hospitals_from_v3
except ImportError:
    def amap_call(*args, **kwargs):
        def decorator(func):
            return func
        return decorator
    def extract_hospitals_from_v3(data):
        return []

try:
    from utils.knowledge_cache import KnowledgeCacheService
    knowledge_cache = KnowledgeCacheService()
except ImportError:
    class MockCache:
        def get_categories(self): return None
        def set_categories(self, data): return True
        def get_articles(self, **kwargs): return None
    knowledge_cache = MockCache()

import json

@amap_call
def index(request):
    """首页"""
    context = {
        'title': '京东医疗 - 专业医疗健康服务平台',
        'features': [
            {
                'icon': 'icon-hospital',
                'title': '在线咨询',
                'description': '7x24小时专业医生在线服务'
            },
            {
                'icon': 'icon-drug',
                'title': '药品配送',
                'description': '正品药品，快速配送到家'
            },
            {
                'icon': 'icon-health',
                'title': '健康管理',
                'description': '个性化健康方案定制'
            },
            {
                'icon': 'icon-report',
                'title': '体检报告',
                'description': '专业体检报告解读服务'
            }
        ]
    }
    return JsonResponse({
        "code": 0,
        "msg": "获取成功",
        "data": context
    }, status=200)

@csrf_exempt
@require_http_methods(["GET", "OPTIONS"])
def get_knowledge_categories(request):
    """获取知识库分类 - 支持Redis缓存"""
    if request.method == "OPTIONS":
        return JsonResponse({}, status=200)
    
    try:
        # 先尝试从缓存获取
        cached_categories = knowledge_cache.get_categories()
        if cached_categories:
            return JsonResponse({
                "code": 0,
                "msg": "获取成功（缓存）",
                "data": cached_categories
            }, status=200)
        
        # 静态分类数据 - 为Redis缓存预留接口
        categories = [
            {
                'id': 1,
                'name': '常见疾病',
                'icon': '🩺',
                'description': '感冒、发烧、头痛等常见疾病的预防和治疗',
                'article_count': 3
            },
            {
                'id': 2,
                'name': '健康养生',
                'icon': '🌱',
                'description': '日常保健、养生之道、健康生活方式',
                'article_count': 2
            },
            {
                'id': 3,
                'name': '营养饮食',
                'icon': '🥗',
                'description': '营养搭配、食疗养生、健康饮食指导',
                'article_count': 6
            },
            {
                'id': 4,
                'name': '运动健身',
                'icon': '💪',
                'description': '运动指导、健身计划、康复训练',
                'article_count': 1
            },
            {
                'id': 5,
                'name': '心理健康',
                'icon': '🧠',
                'description': '心理调节、情绪管理、压力缓解',
                'article_count': 1
            },
            {
                'id': 6,
                'name': '妇幼保健',
                'icon': '👶',
                'description': '孕期保健、育儿知识、妇女健康',
                'article_count': 1
            },
            {
                'id': 7,
                'name': '中医养生',
                'icon': '🌿',
                'description': '中医理论、穴位保健、药膳食疗',
                'article_count': 1
            },
            {
                'id': 8,
                'name': '急救知识',
                'icon': '🚑',
                'description': '急救技能、应急处理、安全防护',
                'article_count': 1
            },
            {
                'id': 9,
                'name': '用药指南',
                'icon': '💊',
                'description': '合理用药、药物安全、用药禁忌',
                'article_count': 1
            },
            {
                'id': 10,
                'name': '体检指南',
                'icon': '📋',
                'description': '体检项目、报告解读、健康评估',
                'article_count': 1
            }
        ]
        
        # 缓存数据
        knowledge_cache.set_categories(categories)
        
        return JsonResponse({
            "code": 0,
            "msg": "获取成功",
            "data": categories
        }, status=200)
        
    except Exception as e:
        return JsonResponse({
            "code": 500,
            "msg": f"服务器错误: {str(e)}",
            "data": None
        }, status=500)

@csrf_exempt
@require_http_methods(["GET", "OPTIONS"])
def get_departments(request):
    """获取医院科室列表 - 从数据库读取"""
    if request.method == "OPTIONS":
        return JsonResponse({}, status=200)
    
    try:
        # 从数据库中获取科室数据
        from .models import Department
        
        departments = Department.objects.filter(is_active=True).annotate(
            doctor_count=Count('doctor', filter=Q(doctor__status='active'))
        )
        
        departments_data = []
        for dept in departments:
            departments_data.append({
                'id': dept.id,
                'name': dept.name,
                'icon': dept.icon,
                'description': dept.description or f'{dept.name}疾病诊断与治疗',
                'doctor_count': dept.doctor_count
            })
        
        return JsonResponse({
            "code": 0,
            "msg": "获取成功",
            "data": departments_data
        }, status=200)
        
    except Exception as e:
        return JsonResponse({
            "code": 500,
            "msg": f"服务器错误: {str(e)}",
            "data": None
        }, status=500)

@csrf_exempt
@require_http_methods(["GET", "OPTIONS"])
def get_doctors_by_department(request, department_id):
    """根据科室获取医生列表 - 从数据库读取"""
    if request.method == "OPTIONS":
        return JsonResponse({}, status=200)
    
    try:
        from .models import Department, Doctor
        
        # 获取科室信息
        try:
            department = Department.objects.get(id=department_id, is_active=True)
        except Department.DoesNotExist:
            return JsonResponse({
                "code": 404,
                "msg": "科室不存在",
                "data": None
            }, status=404)
        
        # 获取该科室的医生列表
        doctors = Doctor.objects.filter(
            department=department,
            status='active'
        ).order_by('-is_featured', '-rating', 'name')
        
        doctors_data = []
        for doctor in doctors:
            # 处理职称显示
            title_display = doctor.get_title_display()
            
            # 处理擅长领域
            specialties = doctor.specialties if doctor.specialties else []
            
            # 生成默认头像（如果没有设置）
            avatar = doctor.avatar or f'https://via.placeholder.com/100x100/2196F3/ffffff?text={doctor.name[0]}'
            
            doctors_data.append({
                'id': doctor.id,
                'name': doctor.name,
                'title': title_display,
                'department': department.name,
                'specialties': specialties,
                'experience': doctor.experience_years,
                'avatar': avatar,
                'rating': float(doctor.rating),
                'consultation_fee': float(doctor.consultation_fee),
                'introduction': doctor.introduction or f'{doctor.name}医生在{department.name}领域拥有丰富的临床经验',
                'education': doctor.education,
                'hospital': doctor.hospital,
                'license_number': doctor.license_number,
                'is_featured': doctor.is_featured,
                'rating_count': doctor.rating_count
            })
        
        department_info = {
            'id': department.id,
            'name': department.name,
            'description': department.description,
            'icon': department.icon
        }
        
        return JsonResponse({
            "code": 0,
            "msg": "获取成功",
            "data": {
                'department': department_info,
                'doctors': doctors_data,
                'total': len(doctors_data)
            }
        }, status=200)
        
    except Exception as e:
        return JsonResponse({
            "code": 500,
            "msg": f"服务器错误: {str(e)}",
            "data": None
        }, status=500)

@csrf_exempt
@require_http_methods(["GET", "OPTIONS"])
def get_knowledge_articles(request):
    """获取知识库文章列表 - 支持Redis缓存"""
    if request.method == "OPTIONS":
        return JsonResponse({}, status=200)
    
    try:
        category_id = request.GET.get('category_id')
        search_query = request.GET.get('search', '')
        sort_by = request.GET.get('sort', 'latest')
        page = int(request.GET.get('page', 1))
        page_size = int(request.GET.get('page_size', 12))
        
        # 丰富的静态数据
        articles = [
            # 常见疾病分类 (category_id: 1)
            {
                'id': 1,
                'title': '春季感冒高发期，如何有效预防？',
                'summary': '春季气温变化大，是感冒高发期。本文将详细介绍春季感冒的预防方法和注意事项。',
                'cover': 'https://via.placeholder.com/400x250/4CAF50/ffffff?text=春季感冒预防',
                'category': '常见疾病',
                'category_id': 1,
                'author': {
                    'name': '李明华',
                    'title': '内科主任医师',
                    'avatar': 'https://via.placeholder.com/40x40/2196F3/ffffff?text=李'
                },
                'publish_date': '2024-03-15',
                'read_count': 1250,
                'like_count': 89,
                'tags': ['感冒', '预防', '春季', '免疫力']
            },
            {
                'id': 2,
                'title': '高血压患者的日常饮食指南',
                'summary': '高血压是常见的慢性疾病，合理的饮食对控制血压至关重要。',
                'cover': 'https://via.placeholder.com/400x250/FF9800/ffffff?text=高血压饮食',
                'category': '常见疾病',
                'category_id': 1,
                'author': {
                    'name': '王建国',
                    'title': '心血管专家',
                    'avatar': 'https://via.placeholder.com/40x40/9C27B0/ffffff?text=王'
                },
                'publish_date': '2024-03-12',
                'read_count': 980,
                'like_count': 67,
                'tags': ['高血压', '饮食', '健康', '控制血压']
            },
            {
                'id': 3,
                'title': '糖尿病患者如何科学监测血糖',
                'summary': '血糖监测是糖尿病管理的重要环节。了解正确的监测方法和时间点。',
                'cover': 'https://via.placeholder.com/400x250/E91E63/ffffff?text=血糖监测',
                'category': '常见疾病',
                'category_id': 1,
                'author': {
                    'name': '陈美丽',
                    'title': '内分泌科主任',
                    'avatar': 'https://via.placeholder.com/40x40/FF5722/ffffff?text=陈'
                },
                'publish_date': '2024-03-10',
                'read_count': 856,
                'like_count': 73,
                'tags': ['糖尿病', '血糖', '监测', '控制']
            },

            # 健康养生分类 (category_id: 2)
            {
                'id': 4,
                'title': '如何调整作息时间，提高睡眠质量',
                'summary': '规律的作息时间是健康生活的基础。学会科学地安排作息。',
                'cover': 'https://via.placeholder.com/400x250/2196F3/ffffff?text=作息调整',
                'category': '健康养生',
                'category_id': 2,
                'author': {
                    'name': '李静蓉',
                    'title': '睡眠医学专家',
                    'avatar': 'https://via.placeholder.com/40x40/8BC34A/ffffff?text=李'
                },
                'publish_date': '2024-03-14',
                'read_count': 1456,
                'like_count': 123,
                'tags': ['作息', '睡眠', '调整', '健康']
            },
            {
                'id': 5,
                'title': '四季养生之道：春夏秋冬各不同',
                'summary': '中医讲究顺应自然，不同季节有不同的养生重点。',
                'cover': 'https://via.placeholder.com/400x250/4CAF50/ffffff?text=四季养生',
                'category': '健康养生',
                'category_id': 2,
                'author': {
                    'name': '王德华',
                    'title': '中医内科主任',
                    'avatar': 'https://via.placeholder.com/40x40/FF9800/ffffff?text=王'
                },
                'publish_date': '2024-03-11',
                'read_count': 1234,
                'like_count': 98,
                'tags': ['四季养生', '中医', '自然', '预防']
            },

            # 营养饮食分类 (category_id: 3) - 丰富的健康饮食内容
            {
                'id': 6,
                'title': '均衡营养饮食指南：吃出健康的一天',
                'summary': '均衡的营养是健康的基础。学会合理搭配饮食，控制热量摄入，保证身体所需的各种营养素。',
                'cover': 'https://via.placeholder.com/400x250/4CAF50/ffffff?text=均衡营养',
                'category': '营养饮食',
                'category_id': 3,
                'author': {
                    'name': '杨丽华',
                    'title': '营养学专家',
                    'avatar': 'https://via.placeholder.com/40x40/4CAF50/ffffff?text=杨'
                },
                'publish_date': '2024-03-13',
                'read_count': 1789,
                'like_count': 145,
                'tags': ['均衡营养', '饮食指南', '健康', '营养素']
            },
            {
                'id': 14,
                'title': '健康饮食搭配原则：营养素的完美组合',
                'summary': '健康饮食不仅要营养均衡，更要懂得搭配。蛋白质、碳水化合物、脂肪、维生素的科学搭配，让每一餐都更有营养价值。',
                'cover': 'https://via.placeholder.com/400x250/FF9800/ffffff?text=健康搭配',
                'category': '营养饮食',
                'category_id': 3,
                'author': {
                    'name': '陈营养师',
                    'title': '临床营养师',
                    'avatar': 'https://via.placeholder.com/40x40/FF9800/ffffff?text=陈'
                },
                'publish_date': '2024-03-12',
                'read_count': 1567,
                'like_count': 132,
                'tags': ['健康饮食', '营养搭配', '蛋白质', '维生素']
            },
            {
                'id': 15,
                'title': '季节性健康饮食：春季养肝正当时',
                'summary': '春季万物复苏，是养肝护肝的最佳时节。选择合适的食材，调整饮食结构，让身体在春天焕发新的活力。',
                'cover': 'https://via.placeholder.com/400x250/8BC34A/ffffff?text=春季养肝',
                'category': '营养饮食',
                'category_id': 3,
                'author': {
                    'name': '王春梅',
                    'title': '中医营养师',
                    'avatar': 'https://via.placeholder.com/40x40/8BC34A/ffffff?text=王'
                },
                'publish_date': '2024-03-11',
                'read_count': 1234,
                'like_count': 98,
                'tags': ['季节饮食', '春季养肝', '健康饮食', '中医营养']
            },
            {
                'id': 16,
                'title': '办公室健康饮食指南：工作餐这样吃更健康',
                'summary': '上班族经常面临饮食不规律的问题。学会选择健康的工作餐，合理安排一日三餐时间，让忙碌的工作生活也能保持健康饮食。',
                'cover': 'https://via.placeholder.com/400x250/2196F3/ffffff?text=办公室饮食',
                'category': '营养饮食',
                'category_id': 3,
                'author': {
                    'name': '李健康',
                    'title': '职场营养顾问',
                    'avatar': 'https://via.placeholder.com/40x40/2196F3/ffffff?text=李'
                },
                'publish_date': '2024-03-10',
                'read_count': 1456,
                'like_count': 124,
                'tags': ['办公室饮食', '工作餐', '健康饮食', '上班族']
            },
            {
                'id': 17,
                'title': '抗氧化食物清单：延缓衰老的天然良药',
                'summary': '抗氧化食物能够清除体内自由基，延缓老化过程。蓝莓、绿茶、坚果、深色蔬菜等富含抗氧化物质的食物，是天然的抗衰老选择。',
                'cover': 'https://via.placeholder.com/400x250/9C27B0/ffffff?text=抗氧化食物',
                'category': '营养饮食',
                'category_id': 3,
                'author': {
                    'name': '张抗衰',
                    'title': '食疗养生专家',
                    'avatar': 'https://via.placeholder.com/40x40/9C27B0/ffffff?text=张'
                },
                'publish_date': '2024-03-09',
                'read_count': 1678,
                'like_count': 156,
                'tags': ['抗氧化', '抗衰老', '健康饮食', '自由基']
            },
            {
                'id': 18,
                'title': '补血养颜饮食秘籍：女性健康饮食指南',
                'summary': '女性朋友容易出现气血不足的情况，影响美容和健康。红枣、桂圆、阿胶、猪肝等补血食物的科学搭配，让你由内而外散发健康光泽。',
                'cover': 'https://via.placeholder.com/400x250/E91E63/ffffff?text=补血养颜',
                'category': '营养饮食',
                'category_id': 3,
                'author': {
                    'name': '美丽营养师',
                    'title': '女性健康专家',
                    'avatar': 'https://via.placeholder.com/40x40/E91E63/ffffff?text=美'
                },
                'publish_date': '2024-03-08',
                'read_count': 1345,
                'like_count': 145,
                'tags': ['补血', '养颜', '女性健康', '健康饮食']
            },

            # 运动健身分类 (category_id: 4)
            {
                'id': 7,
                'title': '有氧运动的好处与实践指南',
                'summary': '有氧运动是最佳的心血管锻炼方式。了解不同类型的有氧运动。',
                'cover': 'https://via.placeholder.com/400x250/4CAF50/ffffff?text=有氧运动',
                'category': '运动健身',
                'category_id': 4,
                'author': {
                    'name': '陈明光',
                    'title': '运动医学专家',
                    'avatar': 'https://via.placeholder.com/40x40/4CAF50/ffffff?text=陈'
                },
                'publish_date': '2024-03-12',
                'read_count': 1567,
                'like_count': 134,
                'tags': ['有氧运动', '心血管', '锻炼', '心肺功能']
            },

            # 心理健康分类 (category_id: 5)
            {
                'id': 8,
                'title': '焦虑症的识别与自我管理',
                'summary': '焦虑症是常见的心理障碍。学会识别焦虑症状，掌握有效的自我管理技巧。',
                'cover': 'https://via.placeholder.com/400x250/9C27B0/ffffff?text=焦虑管理',
                'category': '心理健康',
                'category_id': 5,
                'author': {
                    'name': '王美丽',
                    'title': '心理咨询师',
                    'avatar': 'https://via.placeholder.com/40x40/9C27B0/ffffff?text=王'
                },
                'publish_date': '2024-03-11',
                'read_count': 1445,
                'like_count': 112,
                'tags': ['焦虑症', '心理健康', '自我管理', '情绪管理']
            },

            # 妇幼保健分类 (category_id: 6)
            {
                'id': 9,
                'title': '孕期营养指南：妈妈和宝宝的健康饮食',
                'summary': '孕期营养关系到母婴双方的健康。了解孕期各阶段的营养需求。',
                'cover': 'https://via.placeholder.com/400x250/E91E63/ffffff?text=孕期营养',
                'category': '妇幼保健',
                'category_id': 6,
                'author': {
                    'name': '张丽华',
                    'title': '产科主任医师',
                    'avatar': 'https://via.placeholder.com/40x40/E91E63/ffffff?text=张'
                },
                'publish_date': '2024-03-10',
                'read_count': 1356,
                'like_count': 124,
                'tags': ['孕期营养', '母婴健康', '饮食指南', '孕妇']
            },

            # 中医养生分类 (category_id: 7)
            {
                'id': 10,
                'title': '体质调理与中医养生',
                'summary': '中医讲究因人而宜，不同体质的人需要不同的调理方法。',
                'cover': 'https://via.placeholder.com/400x250/795548/ffffff?text=体质调理',
                'category': '中医养生',
                'category_id': 7,
                'author': {
                    'name': '朱德华',
                    'title': '中医内科主任',
                    'avatar': 'https://via.placeholder.com/40x40/795548/ffffff?text=朱'
                },
                'publish_date': '2024-03-09',
                'read_count': 1087,
                'like_count': 87,
                'tags': ['体质调理', '中医养生', '因人而宜', '中医']
            },

            # 急救知识分类 (category_id: 8)
            {
                'id': 11,
                'title': '心肺复苏(CPR)正确操作步骤',
                'summary': '心肺复苏是救命的关键技能。学会正确的CPR操作步骤和注意事项。',
                'cover': 'https://via.placeholder.com/400x250/F44336/ffffff?text=心肺复苏',
                'category': '急救知识',
                'category_id': 8,
                'author': {
                    'name': '张健强',
                    'title': '急诊科主任',
                    'avatar': 'https://via.placeholder.com/40x40/F44336/ffffff?text=张'
                },
                'publish_date': '2024-03-08',
                'read_count': 1567,
                'like_count': 145,
                'tags': ['心肺复苏', 'CPR', '急救', '生命救助']
            },

            # 用药指南分类 (category_id: 9)
            {
                'id': 12,
                'title': '家庭常用药品存储与使用指南',
                'summary': '家庭常备药箱应该如何配置？了解常用药物的作用、用法和存储方法。',
                'cover': 'https://via.placeholder.com/400x250/00BCD4/ffffff?text=家庭用药',
                'category': '用药指南',
                'category_id': 9,
                'author': {
                    'name': '张药师',
                    'title': '临床药师',
                    'avatar': 'https://via.placeholder.com/40x40/00BCD4/ffffff?text=张'
                },
                'publish_date': '2024-03-07',
                'read_count': 1345,
                'like_count': 115,
                'tags': ['家庭用药', '药品存储', '用药安全', '常用药']
            },

            # 体检指南分类 (category_id: 10)
            {
                'id': 13,
                'title': '年度体检项目解读：了解自己的健康状况',
                'summary': '体检报告中的各项指标都代表什么意思？学会解读体检报告。',
                'cover': 'https://via.placeholder.com/400x250/009688/ffffff?text=体检解读',
                'category': '体检指南',
                'category_id': 10,
                'author': {
                    'name': '陈美丽',
                    'title': '体检科主任',
                    'avatar': 'https://via.placeholder.com/40x40/009688/ffffff?text=陈'
                },
                'publish_date': '2024-03-06',
                'read_count': 1245,
                'like_count': 103,
                'tags': ['体检解读', '健康指标', '体检报告', '健康管理']
            }
        ]
        
        # 筛选文章
        filtered_articles = articles
        if category_id:
            filtered_articles = [art for art in articles if art['category_id'] == int(category_id)]
        
        if search_query:
            filtered_articles = [art for art in filtered_articles 
                               if search_query.lower() in art['title'].lower() 
                               or search_query.lower() in art['summary'].lower()]
        
        # 排序
        if sort_by == 'latest':
            filtered_articles.sort(key=lambda x: x['publish_date'], reverse=True)
        elif sort_by == 'popular':
            filtered_articles.sort(key=lambda x: x['read_count'], reverse=True)
        elif sort_by == 'likes':
            filtered_articles.sort(key=lambda x: x['like_count'], reverse=True)
        
        # 分页
        total = len(filtered_articles)
        start = (page - 1) * page_size
        end = start + page_size
        paged_articles = filtered_articles[start:end]
        
        result = {
            'articles': paged_articles,
            'pagination': {
                'current_page': page,
                'page_size': page_size,
                'total': total,
                'total_pages': (total + page_size - 1) // page_size
            }
        }
        
        return JsonResponse({
            "code": 0,
            "msg": "获取成功",
            "data": result
        }, status=200)
        
    except Exception as e:
        return JsonResponse({
            "code": 500,
            "msg": f"服务器错误: {str(e)}",
            "data": None
        }, status=500)

@csrf_exempt
@require_http_methods(["GET", "OPTIONS"])
def list_hospitals(request):
    """高德地点检索：GET /api/map/hospitals?city=北京&keywords=医院

    使用装饰器统一key/重试，默认关键词为"医院"。
    """
    if request.method == "OPTIONS":
        return JsonResponse({}, status=200)

    try:
        api_key = getattr(settings, 'AMAP_KEY', None) or '5696bda08f34d11fcb4b179d5879cf4a'

        @amap_call(api_key=api_key, timeout=6, retries=2)
        def place_text(city: str, keywords: str, page: int = 1, location: str = None):
            return (
                'https://restapi.amap.com/v3/place/text',
                {
                    'city': city,
                    'keywords': keywords,
                    'types': '090000',  # 医疗保健服务
                    'page': page,
                    'offset': 20,
                    'extensions': 'all',      # 返回扩展信息(biz_ext.rating 等)
                    'sortrule': 'distance',   # 按距离排序并返回 distance
                    **({'location': location} if location else {}),
                }
            )

        city = request.GET.get('city', '')
        keywords = request.GET.get('keywords', '医院')
        # 允许前端传入当前坐标以便返回 distance
        location = request.GET.get('location')  # 'lng,lat'
        data = place_text(city, keywords, page=1, location=location)
        items = extract_hospitals_from_v3(data)

        return JsonResponse({
            'code': 0,
            'msg': 'ok',
            'data': items
        }, status=200)
    except Exception as e:
        return JsonResponse({'code': 500, 'msg': str(e), 'data': None}, status=500)

@csrf_exempt
@require_http_methods(["GET", "OPTIONS"])
def get_doctor_detail(request, doctor_id):
    """获取医生详细信息"""
    if request.method == "OPTIONS":
        return JsonResponse({}, status=200)
    
    try:
        from .models import Doctor
        
        try:
            doctor = Doctor.objects.select_related('department').get(id=doctor_id, status='active')
        except Doctor.DoesNotExist:
            return JsonResponse({
                "code": 404,
                "msg": "医生不存在",
                "data": None
            }, status=404)
        
        # 生成默认头像（如果没有设置）
        avatar = doctor.avatar or f'https://via.placeholder.com/200x200/2196F3/ffffff?text={doctor.name[0]}'
        
        doctor_data = {
            'id': doctor.id,
            'name': doctor.name,
            'title': doctor.get_title_display(),
            'department': doctor.department.name,  # 只显示科室名称
            'specialties': doctor.specialties if doctor.specialties else [],
            'experience_years': doctor.experience_years,
            'avatar': avatar,
            'rating': float(doctor.rating),
            'rating_count': doctor.rating_count,
            'consultation_fee': float(doctor.consultation_fee),
            'introduction': doctor.introduction or f'{doctor.name}医生在{doctor.department.name}领域拥有丰富的临床经验',
            'education': doctor.education,
            'hospital': doctor.hospital,
            'license_number': doctor.license_number,
            'is_featured': doctor.is_featured
        }
        
        return JsonResponse({
            "code": 0,
            "msg": "获取成功",
            "data": doctor_data
        }, status=200)
        
    except Exception as e:
        return JsonResponse({
            "code": 500,
            "msg": f"服务器错误: {str(e)}",
            "data": None
        }, status=500)

@csrf_exempt
@require_http_methods(["GET", "OPTIONS"])
def get_doctor_available_times(request, doctor_id):
    """获取医生可预约时间"""
    if request.method == "OPTIONS":
        return JsonResponse({}, status=200)
    
    try:
        from .models import Doctor
        from datetime import datetime, timedelta
        
        try:
            doctor = Doctor.objects.get(id=doctor_id, status='active')
        except Doctor.DoesNotExist:
            return JsonResponse({
                "code": 404,
                "msg": "医生不存在",
                "data": None
            }, status=404)
        
        # 生成未来7天的可预约时间（示例数据）
        available_times = []
        today = datetime.now().date()
        
        for i in range(7):
            date = today + timedelta(days=i)
            # 跳过周日
            if date.weekday() == 6:
                continue
                
            date_str = date.strftime('%Y-%m-%d')
            day_name = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'][date.weekday()]
            
            # 上午时段
            morning_slots = []
            for hour in range(9, 12):
                for minute in [0, 30]:
                    time_str = f"{hour:02d}:{minute:02d}"
                    morning_slots.append({
                        'time': time_str,
                        'available': True,
                        'period': 'morning'
                    })
            
            # 下午时段
            afternoon_slots = []
            for hour in range(14, 17):
                for minute in [0, 30]:
                    time_str = f"{hour:02d}:{minute:02d}"
                    afternoon_slots.append({
                        'time': time_str,
                        'available': True,
                        'period': 'afternoon'
                    })
            
            available_times.append({
                'date': date_str,
                'day_name': day_name,
                'morning': morning_slots,
                'afternoon': afternoon_slots
            })
        
        return JsonResponse({
            "code": 0,
            "msg": "获取成功",
            "data": {
                'doctor': {
                    'id': doctor.id,
                    'name': doctor.name,
                    'title': doctor.get_title_display()
                },
                'available_times': available_times
            }
        }, status=200)
        
    except Exception as e:
        return JsonResponse({
            "code": 500,
            "msg": f"服务器错误: {str(e)}",
            "data": None
        }, status=500)

@csrf_exempt
@require_http_methods(["POST", "OPTIONS"])
def create_appointment(request):
    """创建预约"""
    if request.method == "OPTIONS":
        return JsonResponse({}, status=200)
    
    try:
        # 获取当前用户
        from utils.JWTTool import jwtTool
        auth_header = request.META.get('HTTP_AUTHORIZATION', '')
        print(f"[预约API] Authorization header: {auth_header}")
        
        token = auth_header.replace('Bearer ', '') if auth_header.startswith('Bearer ') else auth_header
        print(f"[预约API] 提取的token: {token[:20] if token else 'None'}...")
        
        if not token:
            print("[预约API] 未找到Authorization header，返回401")
            return JsonResponse({
                "code": 401,
                "msg": "未登录，请先登录",
                "data": None
            }, status=401)
        
        try:
            payload = jwtTool.decode_token(token)
            user_id = payload.get('user_id')
            print(f"[预约API] Token验证成功，用户ID: {user_id}")
        except Exception as e:
            print(f"[预约API] Token验证失败: {str(e)}")
            return JsonResponse({
                "code": 401,
                "msg": "token无效，请重新登录",
                "data": None
            }, status=401)
        
        data = json.loads(request.body)
        doctor_id = data.get('doctor_id')
        date = data.get('date')
        time = data.get('time')
        patient_name = data.get('patient_name')
        patient_phone = data.get('patient_phone')
        symptoms = data.get('symptoms', '')
        
        # 验证必填字段
        if not all([doctor_id, date, time, patient_name, patient_phone]):
            return JsonResponse({
                "code": 400,
                "msg": "请填写完整的预约信息",
                "data": None
            }, status=400)
        
        # 验证医生是否存在
        from .models import Doctor, Appointment
        from datetime import datetime
        import uuid
        
        try:
            doctor = Doctor.objects.get(id=doctor_id, status='active')
        except Doctor.DoesNotExist:
            return JsonResponse({
                "code": 404,
                "msg": "医生不存在",
                "data": None
            }, status=404)
        
        # 生成预约号
        appointment_no = f"APT{datetime.now().strftime('%Y%m%d%H%M%S')}{str(uuid.uuid4())[:6].upper()}"
        
        # 合并日期和时间
        appointment_datetime = datetime.strptime(f"{date} {time}", "%Y-%m-%d %H:%M")
        
        # 创建预约记录
        appointment = Appointment.objects.create(
            appointment_no=appointment_no,
            user_id=user_id,  # 使用当前登录用户ID
            doctor=doctor,
            appointment_type='online',
            appointment_date=appointment_datetime,
            symptoms=symptoms,
            fee=doctor.consultation_fee,
            status='pending'
        )
        
        appointment_data = {
            'id': appointment.id,
            'appointment_no': appointment.appointment_no,
            'doctor': {
                'id': doctor.id,
                'name': doctor.name,
                'title': doctor.get_title_display(),
                'department': doctor.department.name
            },
            'patient_name': patient_name,
            'patient_phone': patient_phone,
            'appointment_date': appointment.appointment_date.strftime('%Y-%m-%d'),
            'appointment_time': appointment.appointment_date.strftime('%H:%M'),
            'symptoms': symptoms,
            'fee': float(appointment.fee),
            'status': appointment.get_status_display(),
            'created_at': appointment.created_at.strftime('%Y-%m-%d %H:%M:%S')
        }
        
        return JsonResponse({
            "code": 0,
            "msg": "预约成功！请等待医院确认",
            "data": appointment_data
        }, status=200)
        
    except json.JSONDecodeError:
        return JsonResponse({
            "code": 400,
            "msg": "请求数据格式错误",
            "data": None
        }, status=400)
    except Exception as e:
        return JsonResponse({
            "code": 500,
            "msg": f"服务器错误: {str(e)}",
            "data": None
        }, status=500)

@csrf_exempt
@require_http_methods(["POST", "OPTIONS"])
def create_appointment_simple(request):
    """创建预约(简化版本，不需要token)"""
    if request.method == "OPTIONS":
        return JsonResponse({}, status=200)
    
    try:
        data = json.loads(request.body)
        doctor_id = data.get('doctor_id')
        date = data.get('date')
        time = data.get('time')
        patient_name = data.get('patient_name')
        patient_phone = data.get('patient_phone')
        symptoms = data.get('symptoms', '')
        
        print(f"[预约API简化版] 接收数据: doctor_id={doctor_id}, date={date}, time={time}")
        
        # 验证必填字段
        if not all([doctor_id, date, time, patient_name, patient_phone]):
            return JsonResponse({
                "code": 400,
                "msg": "请填写完整的预约信息",
                "data": None
            }, status=400)
        
        from .models import Doctor, Appointment
        from datetime import datetime
        import uuid
        
        try:
            doctor = Doctor.objects.get(id=doctor_id, status='active')
        except Doctor.DoesNotExist:
            return JsonResponse({
                "code": 404,
                "msg": "医生不存在",
                "data": None
            }, status=404)
        
        # 生成预约号
        appointment_no = f"APT{datetime.now().strftime('%Y%m%d%H%M%S')}{str(uuid.uuid4())[:6].upper()}"
        
        # 合并日期和时间
        appointment_datetime = datetime.strptime(f"{date} {time}", "%Y-%m-%d %H:%M")
        
        # 创建预约记录
        # 尝试从请求中获取用户ID
        from utils.JWTTool import jwtTool
        auth_header = request.META.get('HTTP_AUTHORIZATION', '')
        token = auth_header.replace('Bearer ', '') if auth_header.startswith('Bearer ') else auth_header
        
        user_id = 1  # 默认用户ID
        if token:
            try:
                payload = jwtTool.decode_token(token)
                user_id = payload.get('user_id', 1)
                print(f"[预约API简化版] 使用用户ID: {user_id}")
            except:
                print("[预约API简化版] Token解析失败，使用默认用户ID")
        
        appointment = Appointment.objects.create(
            appointment_no=appointment_no,
            user_id=user_id,  # 使用解析到的用户ID
            doctor=doctor,
            appointment_type='online',
            appointment_date=appointment_datetime,
            symptoms=symptoms,
            fee=doctor.consultation_fee,
            status='pending'
        )
        
        print(f"[预约API简化版] 预约创建成功: {appointment.appointment_no}")
        
        appointment_data = {
            'id': appointment.id,
            'appointment_no': appointment.appointment_no,
            'doctor': {
                'id': doctor.id,
                'name': doctor.name,
                'title': doctor.get_title_display(),
                'department': doctor.department.name
            },
            'patient_name': patient_name,
            'patient_phone': patient_phone,
            'appointment_date': appointment.appointment_date.strftime('%Y-%m-%d'),
            'appointment_time': appointment.appointment_date.strftime('%H:%M'),
            'symptoms': symptoms,
            'fee': float(appointment.fee),
            'status': appointment.get_status_display(),
            'created_at': appointment.created_at.strftime('%Y-%m-%d %H:%M:%S')
        }
        
        return JsonResponse({
            "code": 0,
            "msg": "预约成功！请等待医院确认",
            "data": appointment_data
        }, status=200)
        
    except json.JSONDecodeError:
        return JsonResponse({
            "code": 400,
            "msg": "请求数据格式错误",
            "data": None
        }, status=400)
    except Exception as e:
        print(f"[预约API简化版] 异常: {str(e)}")
        return JsonResponse({
            "code": 500,
            "msg": f"服务器错误: {str(e)}",
            "data": None
        }, status=500)

@csrf_exempt
@require_http_methods(["GET", "OPTIONS"])
def get_my_appointments(request):
    """获取用户预约列表"""
    if request.method == "OPTIONS":
        return JsonResponse({}, status=200)
    
    try:
        # 获取当前用户
        from utils.JWTTool import jwtTool
        token = request.META.get('HTTP_AUTHORIZATION', '').replace('Bearer ', '')
        if not token:
            return JsonResponse({
                "code": 401,
                "msg": "未登录，请先登录",
                "data": None
            }, status=401)
        
        try:
            payload = jwtTool.decode_token(token)
            user_id = payload.get('user_id')
        except:
            return JsonResponse({
                "code": 401,
                "msg": "token无效，请重新登录",
                "data": None
            }, status=401)
        
        from .models import Appointment
        
        # 根据当前用户ID获取预约列表
        appointments = Appointment.objects.filter(user_id=user_id).select_related('doctor', 'doctor__department').order_by('-created_at')
        
        appointments_data = []
        for appointment in appointments:
            appointments_data.append({
                'id': appointment.id,
                'appointment_no': appointment.appointment_no,
                'doctor': {
                    'id': appointment.doctor.id,
                    'name': appointment.doctor.name,
                    'title': appointment.doctor.get_title_display(),
                    'department': appointment.doctor.department.name
                },
                'appointment_date': appointment.appointment_date.strftime('%Y-%m-%d %H:%M'),
                'symptoms': appointment.symptoms,
                'fee': float(appointment.fee),
                'status': appointment.get_status_display(),
                'remark': appointment.remark or '',
                'created_at': appointment.created_at.strftime('%Y-%m-%d %H:%M:%S')
            })
        
        return JsonResponse({
            "code": 0,
            "msg": "获取成功",
            "data": appointments_data
        }, status=200)
        
    except Exception as e:
        return JsonResponse({
            "code": 500,
            "msg": f"服务器错误: {str(e)}",
            "data": None
        }, status=500)

@csrf_exempt
@require_http_methods(["GET", "OPTIONS"])
def get_my_appointments_simple(request):
    """获取用户预约列表(简化版本)"""
    if request.method == "OPTIONS":
        return JsonResponse({}, status=200)
    
    try:
        from .models import Appointment
        from utils.JWTTool import jwtTool
        
        # 尝试从请求中获取token
        auth_header = request.META.get('HTTP_AUTHORIZATION', '')
        token = auth_header.replace('Bearer ', '') if auth_header.startswith('Bearer ') else auth_header
        
        user_id = None
        if token:
            try:
                payload = jwtTool.decode_token(token)
                user_id = payload.get('user_id')
                print(f"[预约列表API] 获取到用户ID: {user_id}")
            except Exception as e:
                print(f"[预约列表API] Token解析失败: {str(e)}")
        else:
            print("[预约列表API] 未提供token")
        
        if user_id:
            # 有用户ID，只显示该用户的预约
            appointments = Appointment.objects.filter(user_id=user_id).select_related('doctor', 'doctor__department').order_by('-created_at')
            print(f"[预约列表API] 用户{user_id}找到{appointments.count()}条预约记录")
        else:
            # 没有用户ID，返回空数据
            appointments = Appointment.objects.none()
            print("[预约列表API] 未获取到用户ID，返回空数据")
        
        appointments_data = []
        for appointment in appointments:
            appointments_data.append({
                'id': appointment.id,
                'appointment_no': appointment.appointment_no,
                'doctor': {
                    'id': appointment.doctor.id,
                    'name': appointment.doctor.name,
                    'title': appointment.doctor.get_title_display(),
                    'department': appointment.doctor.department.name
                },
                'appointment_date': appointment.appointment_date.strftime('%Y-%m-%d %H:%M'),
                'symptoms': appointment.symptoms,
                'fee': float(appointment.fee),
                'status': appointment.get_status_display(),
                'remark': appointment.remark or '',
                'created_at': appointment.created_at.strftime('%Y-%m-%d %H:%M:%S')
            })
        
        return JsonResponse({
            "code": 0,
            "msg": "获取成功",
            "data": appointments_data
        }, status=200)
        
    except Exception as e:
        print(f"[预约列表API] 异常: {str(e)}")
        return JsonResponse({
            "code": 500,
            "msg": f"服务器错误: {str(e)}",
            "data": None
        }, status=500)

@csrf_exempt
@require_http_methods(["GET", "OPTIONS"])
def debug_appointments(request):
    """调试预约数据"""
    if request.method == "OPTIONS":
        return JsonResponse({}, status=200)
    
    try:
        from .models import Appointment
        from utils.JWTTool import jwtTool
        
        # 获取token信息
        auth_header = request.META.get('HTTP_AUTHORIZATION', '')
        token = auth_header.replace('Bearer ', '') if auth_header.startswith('Bearer ') else auth_header
        
        debug_info = {
            'auth_header': auth_header,
            'token': token[:20] + '...' if token else 'None',
            'user_id': None,
            'all_appointments': [],
            'filtered_appointments': []
        }
        
        if token:
            try:
                payload = jwtTool.decode_token(token)
                user_id = payload.get('user_id')
                debug_info['user_id'] = user_id
                debug_info['payload'] = payload
            except Exception as e:
                debug_info['token_error'] = str(e)
        
        # 获取所有预约记录
        all_appointments = Appointment.objects.all().values('id', 'user_id', 'appointment_no', 'doctor__name')
        debug_info['all_appointments'] = list(all_appointments)
        
        # 如果有用户ID，获取该用户的预约
        if debug_info['user_id']:
            filtered = Appointment.objects.filter(user_id=debug_info['user_id']).values('id', 'user_id', 'appointment_no', 'doctor__name')
            debug_info['filtered_appointments'] = list(filtered)
        
        return JsonResponse({
            "code": 0,
            "msg": "调试信息",
            "data": debug_info
        }, status=200)
        
    except Exception as e:
        return JsonResponse({
            "code": 500,
            "msg": f"调试错误: {str(e)}",
            "data": None
        }, status=500)


# ===================== 迭代器模式预约管理功能 =====================

@csrf_exempt
@require_http_methods(["POST"])
@login_required
def add_doctor_to_appointments(request):
    """点击医生添加到预约 - 使用迭代器模式处理"""
    try:
        # 详细日志记录
        print(f"Request user: {request.user}")
        print(f"Request user type: {type(request.user)}")
        print(f"Request user is_authenticated: {request.user.is_authenticated}")
        
        # 检查用户认证状态
        if not hasattr(request, 'user') or not request.user.is_authenticated:
            return JsonResponse({
                "code": 401,
                "msg": "用户未登录或认证失败"
            })
        
        data = json.loads(request.body)
        doctor_id = data.get('doctor_id')
        appointment_date = data.get('appointment_date')
        appointment_type = data.get('appointment_type', 'online')
        symptoms = data.get('symptoms', '')
        
        print(f"预约数据: doctor_id={doctor_id}, appointment_date={appointment_date}")
        
        if not doctor_id:
            return JsonResponse({
                "code": 1,
                "msg": "医生ID不能为空"
            })
        
        # 验证医生是否存在
        try:
            doctor = Doctor.objects.get(id=doctor_id, status='active')
        except Doctor.DoesNotExist:
            return JsonResponse({
                "code": 1,
                "msg": "医生不存在或已停诊"
            })
        
        # 使用迭代器检查用户是否已有该医生的预约
        existing_appointments = MedicalDataIteratorFactory.create_appointment_iterator(
            user_id=request.user.id,
            doctor_id=doctor_id,
            status='pending'
        )
        
        has_existing = False
        for appointment in existing_appointments:
            has_existing = True
            break
        
        if has_existing:
            return JsonResponse({
                "code": 1,
                "msg": "您已有该医生的待处理预约，请勿重复预约"
            })
        
        # 生成预约号
        appointment_no = f"AP{datetime.now().strftime('%Y%m%d%H%M%S')}{doctor_id}"
        
        # 处理预约时间
        if appointment_date:
            try:
                # 如果是字符串，尝试解析
                if isinstance(appointment_date, str):
                    appointment_datetime = datetime.strptime(appointment_date, '%Y-%m-%d %H:%M:%S')
                else:
                    appointment_datetime = appointment_date
            except ValueError:
                appointment_datetime = datetime.now()
        else:
            appointment_datetime = datetime.now()
        
        # 创建预约
        appointment = Appointment.objects.create(
            appointment_no=appointment_no,
            user=request.user,
            doctor=doctor,
            appointment_type=appointment_type,
            appointment_date=appointment_datetime,
            symptoms=symptoms,
            fee=doctor.consultation_fee,
            status='pending'
        )
        
        # 使用迭代器获取用户所有预约进行统计
        user_appointments_iterator = MedicalDataIteratorFactory.create_appointment_iterator(
            user_id=request.user.id
        )
        
        total_appointments = 0
        pending_count = 0
        for apt in user_appointments_iterator:
            total_appointments += 1
            if apt['status'] == 'pending':
                pending_count += 1
        
        return JsonResponse({
            "code": 0,
            "msg": "预约添加成功",
            "data": {
                "appointment": {
                    "appointment_no": appointment.appointment_no,
                    "doctor_name": doctor.name,
                    "doctor_title": doctor.get_title_display(),
                    "department": doctor.department.name,
                    "fee": float(appointment.fee),
                    "status": appointment.get_status_display(),
                    "appointment_date": appointment.appointment_date.isoformat()
                },
                "statistics": {
                    "total_appointments": total_appointments,
                    "pending_appointments": pending_count
                }
            }
        })
        
    except json.JSONDecodeError:
        return JsonResponse({
            "code": 1,
            "msg": "请求数据格式错误"
        })
    except Exception as e:
        return JsonResponse({
            "code": 500,
            "msg": f"预约失败: {str(e)}"
        })


@csrf_exempt
@require_http_methods(["GET"])
@login_required
def get_my_appointments_with_iterator(request):
    """使用迭代器获取我的预约列表"""
    try:
        group_by = request.GET.get('group_by', 'status')  # status, date, or none
        status_filter = request.GET.get('status')
        
        # 创建预约迭代器
        appointment_iterator = MedicalDataIteratorFactory.create_appointment_iterator(
            user_id=request.user.id,
            status=status_filter
        )
        
        appointments = []
        for appointment in appointment_iterator:
            appointments.append(appointment)
        
        # 如果需要分组
        if group_by and group_by != 'none':
            from utils.data_iterators import AppointmentIterator
            grouped_iterator = AppointmentIterator(appointments, group_by)
            
            groups = []
            for group in grouped_iterator:
                groups.append(group)
            
            return JsonResponse({
                "code": 0,
                "msg": "获取预约成功",
                "data": {
                    "appointments": appointments,
                    "groups": groups,
                    "total": len(appointments),
                    "group_by": group_by
                }
            })
        else:
            return JsonResponse({
                "code": 0,
                "msg": "获取预约成功", 
                "data": {
                    "appointments": appointments,
                    "total": len(appointments)
                }
            })
            
    except Exception as e:
        return JsonResponse({
            "code": 500,
            "msg": f"获取预约失败: {str(e)}"
        })


@csrf_exempt
@require_http_methods(["GET"])
def get_doctors_list(request):
    """获取医生列表 - 基础接口"""
    try:
        # 获取所有活跃医生
        doctors = Doctor.objects.filter(status='active').select_related('department')
        
        doctors_data = []
        for doctor in doctors:
            doctors_data.append({
                "id": doctor.id,
                "name": doctor.name,
                "title": doctor.title,
                "specialty": doctor.specialty,
                "rating": float(doctor.rating) if doctor.rating else 0.0,
                "consultation_fee": float(doctor.consultation_fee) if doctor.consultation_fee else 0.0,
                "department": {
                    "id": doctor.department.id if doctor.department else None,
                    "name": doctor.department.name if doctor.department else "未分科室"
                },
                "hospital": doctor.hospital or "未知医院",
                "status": doctor.status,
                "description": doctor.description or ""
            })
        
        return JsonResponse({
            "code": 0,
            "msg": "获取医生列表成功",
            "data": {
                "doctors": doctors_data,
                "total": len(doctors_data)
            }
        })
        
    except Exception as e:
        print(f"获取医生列表错误: {str(e)}")
        return JsonResponse({
            "code": 500,
            "msg": f"获取医生列表失败: {str(e)}"
        })

@csrf_exempt
@require_http_methods(["GET"])
def get_doctors_with_iterator_filter(request):
    """使用迭代器过滤医生列表"""
    try:
        department_id = request.GET.get('department_id')
        min_rating = request.GET.get('min_rating')
        max_fee = request.GET.get('max_fee')
        page = int(request.GET.get('page', 1))
        page_size = int(request.GET.get('page_size', 12))
        
        # 构建过滤条件
        filters = {}
        if department_id:
            filters['department_id'] = int(department_id)
        if min_rating:
            filters['min_rating'] = float(min_rating)
        if max_fee:
            filters['max_fee'] = float(max_fee)
        
        # 创建医生迭代器
        doctor_iterator = MedicalDataIteratorFactory.create_doctor_iterator(
            **filters,
            status='active'
        )
        
        # 收集所有过滤后的医生
        filtered_doctors = []
        for doctor in doctor_iterator:
            filtered_doctors.append(doctor)
        
        print(f"🔍 过滤后医生数量: {len(filtered_doctors)}")
        print(f"📊 过滤条件: {filters}")
        print(f"📄 分页参数: page={page}, page_size={page_size}")
        
        # 使用分页迭代器
        pagination_iterator = MedicalDataIteratorFactory.create_paginated_iterator(
            filtered_doctors, page_size
        )
        
        # 跳转到指定页
        pagination_iterator.goToPage(page - 1)
        
        try:
            page_data = next(pagination_iterator)
        except StopIteration:
            # 如果没有数据，返回空页面
            page_data = {
                'page': page,
                'totalPages': 0,
                'data': [],
                'hasNext': False,
                'hasPrev': False,
                'totalItems': 0
            }
        
        return JsonResponse({
            "code": 0,
            "msg": "获取医生列表成功",
            "data": {
                "doctors": page_data['data'],
                "pagination": {
                    "current_page": page_data['page'],
                    "total_pages": page_data['totalPages'],
                    "page_size": page_size,
                    "total_items": page_data['totalItems'],
                    "has_next": page_data['hasNext'],
                    "has_prev": page_data['hasPrev']
                },
                "filters_applied": filters
            }
        })
        
    except Exception as e:
        import traceback
        error_details = traceback.format_exc()
        print(f"❌ 医生迭代器API错误: {str(e)}")
        print(f"📋 详细错误信息:\n{error_details}")
        return JsonResponse({
            "code": 500,
            "msg": f"获取医生列表失败: {str(e)}"
        })


@csrf_exempt
@require_http_methods(["POST"])
@login_required
def cancel_appointment_with_iterator(request):
    """使用迭代器取消预约"""
    try:
        data = json.loads(request.body)
        appointment_no = data.get('appointment_no')
        
        if not appointment_no:
            return JsonResponse({
                "code": 1,
                "msg": "预约号不能为空"
            })
        
        # 使用迭代器查找用户的预约
        user_appointments_iterator = MedicalDataIteratorFactory.create_appointment_iterator(
            user_id=request.user.id
        )
        
        target_appointment = None
        for appointment in user_appointments_iterator:
            if appointment['appointment_no'] == appointment_no:
                target_appointment = appointment
                break
        
        if not target_appointment:
            return JsonResponse({
                "code": 1,
                "msg": "预约不存在或不属于您"
            })
        
        # 检查预约状态是否可以取消
        if target_appointment['status'] not in ['pending', 'confirmed']:
            return JsonResponse({
                "code": 1,
                "msg": "该预约状态不允许取消"
            })
        
        # 更新预约状态
        appointment_obj = Appointment.objects.get(appointment_no=appointment_no)
        appointment_obj.status = 'cancelled'
        appointment_obj.save()
        
        # 重新统计用户预约
        updated_iterator = MedicalDataIteratorFactory.create_appointment_iterator(
            user_id=request.user.id
        )
        
        stats = {'total': 0, 'pending': 0, 'confirmed': 0, 'cancelled': 0, 'completed': 0}
        for apt in updated_iterator:
            stats['total'] += 1
            stats[apt['status']] = stats.get(apt['status'], 0) + 1
        
        return JsonResponse({
            "code": 0,
            "msg": "预约取消成功",
            "data": {
                "appointment_no": appointment_no,
                "new_status": "cancelled",
                "statistics": stats
            }
        })
        
    except Appointment.DoesNotExist:
        return JsonResponse({
            "code": 1,
            "msg": "预约不存在"
        })
    except Exception as e:
        return JsonResponse({
            "code": 500,
            "msg": f"取消预约失败: {str(e)}"
        })


# ===================== 测试认证状态 =====================

@csrf_exempt
@require_http_methods(["GET"])
@login_required
def test_auth_status(request):
    """测试用户认证状态"""
    try:
        return JsonResponse({
            "code": 0,
            "msg": "认证成功",
            "data": {
                "user_id": request.user.id,
                "username": request.user.username,
                "is_authenticated": request.user.is_authenticated,
                "user_type": str(type(request.user)),
                "user_info": getattr(request, 'user_info', None)
            }
        })
    except Exception as e:
            return JsonResponse({
                "code": 500,
                "msg": f"认证测试失败: {str(e)}"
            })


@csrf_exempt
@require_http_methods(["POST"])
def add_appointment_simple(request):
    """简化版预约接口 - 用于测试（临时不需要认证）"""
    try:
        data = json.loads(request.body)
        doctor_id = data.get('doctor_id')
        appointment_date = data.get('appointment_date')
        appointment_type = data.get('appointment_type', 'online')
        symptoms = data.get('symptoms', '')
        
        print(f"简化预约: doctor_id={doctor_id}, appointment_date={appointment_date}")
        
        if not doctor_id:
            return JsonResponse({
                "code": 1,
                "msg": "医生ID不能为空"
            })
        
        # 验证医生是否存在
        try:
            doctor = Doctor.objects.get(id=doctor_id, status='active')
        except Doctor.DoesNotExist:
            return JsonResponse({
                "code": 1,
                "msg": "医生不存在或已停诊"
            })
        
        # 临时使用第一个用户进行测试
        from django.contrib.auth import get_user_model
        User = get_user_model()
        try:
            test_user = User.objects.first()
            if not test_user:
                return JsonResponse({
                    "code": 1,
                    "msg": "系统中没有用户，请先创建用户"
                })
        except Exception as e:
            return JsonResponse({
                "code": 1,
                "msg": f"获取测试用户失败: {str(e)}"
            })
        
        # 生成预约号
        appointment_no = f"TEST{datetime.now().strftime('%Y%m%d%H%M%S')}{doctor_id}"
        
        # 处理预约时间
        if appointment_date:
            try:
                if isinstance(appointment_date, str):
                    appointment_datetime = datetime.strptime(appointment_date, '%Y-%m-%d %H:%M:%S')
                else:
                    appointment_datetime = appointment_date
            except ValueError:
                appointment_datetime = datetime.now()
        else:
            appointment_datetime = datetime.now()
        
        # 创建预约
        appointment = Appointment.objects.create(
            appointment_no=appointment_no,
            user=test_user,
            doctor=doctor,
            appointment_type=appointment_type,
            appointment_date=appointment_datetime,
            symptoms=symptoms,
            fee=doctor.consultation_fee,
            status='pending'
        )
        
        return JsonResponse({
            "code": 0,
            "msg": "测试预约创建成功",
            "data": {
                "appointment": {
                    "appointment_no": appointment.appointment_no,
                    "doctor_name": doctor.name,
                    "doctor_title": doctor.get_title_display(),
                    "department": doctor.department.name,
                    "fee": float(appointment.fee),
                    "status": appointment.get_status_display(),
                    "appointment_date": appointment.appointment_date.isoformat()
                },
                "note": "这是测试预约，使用了系统默认用户"
            }
        })
        
    except json.JSONDecodeError:
        return JsonResponse({
            "code": 1,
            "msg": "请求数据格式错误"
        })
    except Exception as e:
        print(f"预约创建错误: {str(e)}")
        return JsonResponse({
            "code": 500,
            "msg": f"预约失败: {str(e)}"
        })
